import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ImageCarouselWidget extends StatefulWidget {
  final List<String> images;
  final bool autoPlay;
  final Duration autoPlayInterval;
  final double height;
  final double previewHeight;
  final VoidCallback? onBack;

  const ImageCarouselWidget({
    Key? key,
    required this.images,
    this.autoPlay = true,
    this.autoPlayInterval = const Duration(seconds: 3),
    this.height = 400,
    this.previewHeight = 80,
    this.onBack,
  }) : super(key: key);

  @override
  State<ImageCarouselWidget> createState() => _ImageCarouselWidgetState();
}

class _ImageCarouselWidgetState extends State<ImageCarouselWidget> {
  late PageController _mainPageController;
  late ScrollController _previewScrollController;
  Timer? _autoPlayTimer;
  int _currentIndex = 0;
  bool _isAutoPlaying = true;

  @override
  void initState() {
    super.initState();
    _mainPageController = PageController();
    _previewScrollController = ScrollController();
    
    if (widget.autoPlay) {
      _startAutoPlay();
    }
  }

  @override
  void didUpdateWidget(ImageCarouselWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 当图片列表或自动播放设置发生变化时，重新启动自动播放
    if (widget.images != oldWidget.images || widget.autoPlay != oldWidget.autoPlay) {
      print('ImageCarousel: 检测到数据变化，重新启动自动播放');
      _stopAutoPlay();
      if (widget.autoPlay && widget.images.length > 1) {
        _startAutoPlay();
      }
    }
  }

  @override
  void dispose() {
    _autoPlayTimer?.cancel();
    _mainPageController.dispose();
    _previewScrollController.dispose();
    super.dispose();
  }

  void _startAutoPlay() {
    if (!widget.autoPlay || widget.images.length <= 1) {
      print('ImageCarousel: 自动播放未启动 - autoPlay: ${widget.autoPlay}, 图片数量: ${widget.images.length}');
      return;
    }
    
    _stopAutoPlay(); // 确保先停止之前的Timer
    _isAutoPlaying = true;
    print('ImageCarousel: 开始自动播放，间隔: ${widget.autoPlayInterval.inSeconds}秒');
    
    _autoPlayTimer = Timer.periodic(widget.autoPlayInterval, (timer) {
      if (!mounted) {
        print('ImageCarousel: 组件已销毁，取消自动播放');
        timer.cancel();
        return;
      }
      
      if (_isAutoPlaying && widget.images.isNotEmpty) {
        final nextIndex = (_currentIndex + 1) % widget.images.length;
        print('ImageCarousel: 自动切换到第${nextIndex + 1}张图片');
        _goToIndex(nextIndex);
      }
    });
  }

  void _stopAutoPlay() {
    print('ImageCarousel: 停止自动播放');
    _autoPlayTimer?.cancel();
    _autoPlayTimer = null;
    _isAutoPlaying = false;
  }

  void _resumeAutoPlay() {
    if (widget.autoPlay && widget.images.length > 1) {
      print('ImageCarousel: 恢复自动播放');
      _startAutoPlay();
    } else {
      print('ImageCarousel: 无法恢复自动播放 - autoPlay: ${widget.autoPlay}, _isAutoPlaying: $_isAutoPlaying, 图片数量: ${widget.images.length}');
    }
  }

  void _goToIndex(int index) {
    if (index < 0 || index >= widget.images.length) return;
    
    setState(() {
      _currentIndex = index;
    });
    
    _mainPageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
    
    _scrollPreviewToIndex(index);
  }

  void _scrollPreviewToIndex(int index) {
    if (!_previewScrollController.hasClients) return;
    
    const itemWidth = 70.0; // 预览图宽度 + 间距
    final screenWidth = MediaQuery.of(context).size.width;
    final maxScroll = _previewScrollController.position.maxScrollExtent;
    
    double targetOffset = (index * itemWidth) - (screenWidth / 2) + (itemWidth / 2);
    targetOffset = targetOffset.clamp(0.0, maxScroll);
    
    _previewScrollController.animateTo(
      targetOffset,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  Widget _buildMainImage() {
    return Container(
      height: widget.height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: Colors.grey[100],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: PageView.builder(
          controller: _mainPageController,
          onPageChanged: (index) {
            setState(() {
              _currentIndex = index;
            });
            _scrollPreviewToIndex(index);
            
            // 用户手动滑动时暂停自动播放，3秒后恢复
            if (_isAutoPlaying) {
              _stopAutoPlay();
              Future.delayed(const Duration(seconds: 3), () {
                if (mounted) {
                  _resumeAutoPlay();
                }
              });
            }
          },
          itemCount: widget.images.length,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: () {
                // 点击图片时暂停自动播放，5秒后恢复
                if (_isAutoPlaying) {
                  _stopAutoPlay();
                  Future.delayed(const Duration(seconds: 5), () {
                    if (mounted) {
                      _resumeAutoPlay();
                    }
                  });
                }
              },
              child: Image.network(
                widget.images[index],
                fit: BoxFit.cover,
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Center(
                    child: CircularProgressIndicator(
                      value: loadingProgress.expectedTotalBytes != null
                          ? loadingProgress.cumulativeBytesLoaded /
                              loadingProgress.expectedTotalBytes!
                          : null,
                    ),
                  );
                },
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[200],
                    child: const Center(
                      child: Icon(
                        Icons.broken_image,
                        size: 50,
                        color: Colors.grey,
                      ),
                    ),
                  );
                },
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildBackButton() {
    if (widget.onBack == null) return const SizedBox.shrink();
    
    return Positioned(
      top: 16,
      left: 16,
      child: GestureDetector(
        onTap: widget.onBack,
        child: Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.5),
            borderRadius: BorderRadius.circular(20),
          ),
          child: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.white,
            size: 20,
          ),
        ),
      ),
    );
  }

  Widget _buildPageIndicator() {
    return Positioned(
      bottom: 2,
      right: 16,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.6),
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          '${_currentIndex + 1}/${widget.images.length}',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  Widget _buildPreviewList() {
    return Positioned(
      bottom: 0.w,
      left: 0,
      right: 0,
      child: Container(
        height: widget.previewHeight,
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.3),
          borderRadius: BorderRadius.circular(12),
        ),
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        padding: EdgeInsets.symmetric(vertical: 8.w),
        child: ListView.builder(
          controller: _previewScrollController,
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          itemCount: widget.images.length,
          itemBuilder: (context, index) {
            final isSelected = index == _currentIndex;
            
            return GestureDetector(
              onTap: () {
                _goToIndex(index);
                // 点击预览图时暂停自动播放，3秒后恢复
                if (_isAutoPlaying) {
                  _stopAutoPlay();
                  Future.delayed(const Duration(seconds: 3), () {
                    if (mounted) {
                      _resumeAutoPlay();
                    }
                  });
                }
              },
              child: Container(
                width: 60.w,
                height: 60.w,
                margin: EdgeInsets.only(right: 10.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: isSelected ? Colors.orange : Colors.transparent,
                    width: 2,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(6),
                  child: Image.network(
                    widget.images[index],
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return Container(
                        color: Colors.grey[200],
                        child: const Center(
                          child: SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          ),
                        ),
                      );
                    },
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey[200],
                        child: const Icon(
                          Icons.broken_image,
                          size: 20,
                          color: Colors.grey,
                        ),
                      );
                    },
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (widget.images.isEmpty) {
      return Container(
        height: widget.height,
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(12),
        ),
        child: const Center(
          child: Text(
            '暂无图片',
            style: TextStyle(
              color: Colors.grey,
              fontSize: 16,
            ),
          ),
        ),
      );
    }

    return Stack(
      children: [
        _buildMainImage(),
        _buildBackButton(),
        // _buildPageIndicator(),
        _buildPreviewList(),
      ],
    );
  }
}

// 使用示例：
// ImageCarouselWidget(
//   images: [
//     'https://example.com/image1.jpg',
//     'https://example.com/image2.jpg',
//     'https://example.com/image3.jpg',
//   ],
//   autoPlay: true,
//   autoPlayInterval: Duration(seconds: 3),
//   height: 400,
//   previewHeight: 80,
//   onBack: () => Navigator.pop(context),
// )